import { Module } from 'vuex'
import router from '@/router/index'
import type { IRootState } from '../type'
import type { ILoginState } from './type'
import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusByRoleId
} from '@/service/login/logih'
import LocalCache from '@/utils/cache'
import { mapMenusToRoutes } from '@/utils/map-menus'

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInofo: {},
      UserMenus: []
    }
  },
  mutations: {
    //修改token
    changeToken(state, token) {
      state.token = token
    },
    changeUseInfoResult(state, userInofo) {
      state.userInofo = userInofo
    },
    changeMenusResult(state, UserMenus) {
      state.UserMenus = UserMenus

      //动态路由 调用封装的函数
      const routers = mapMenusToRoutes(UserMenus)
      //动态添加路由
      routers.forEach((route) => {
        router.addRoute('main', route)
      })
    }
  },
  actions: {
    async accountLoginAction({ commit }, payload: any) {
      //1登录逻辑
      const loginResult = await accountLoginRequest(payload)
      //保存token和id
      const { id, token } = loginResult.data
      commit('changeToken', token)
      LocalCache.setCache('token', token)

      //2请求用户信息
      const userInofoResult = await requestUserInfoById(id)
      const userInofo = userInofoResult.data
      commit('changeUseInfoResult', userInofo)
      LocalCache.setCache('userInofo', userInofo)

      //3请求用户菜单
      const useMenusResult = await requestUserMenusByRoleId(userInofo.role.id)
      const UserMenus = useMenusResult.data
      commit('changeMenusResult', UserMenus)
      LocalCache.setCache('UserMenus', UserMenus)

      //4登录完成跳转到首页
      router.push('/main')
    },
    //定义一个方法解决用户刷新浏览器导致vuex里保存的数据丢失
    LoadLocalLogin({ commit }) {
      const token = LocalCache.getCache('token')
      if (token) {
        commit('changeToken', token)
      }
      const userInofo = LocalCache.getCache('userInofo')
      if (userInofo) {
        commit('changeUseInfoResult', userInofo)
      }
      const UserMenus = LocalCache.getCache('UserMenus')
      if (UserMenus) {
        commit('changeMenusResult', UserMenus)
      }
    }

    // phoneLoginAction({ ...commit }, payload: any) {
    //   console.log('执行phoneLoginAction', payload)
    // }
  },
  modules: {}
}
export default loginModule
